package deibay.server.network.socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;

import deibay.DeibayLogger;
import deibay.network.ServerCommunicator;
import deibay.server.network.Session;


public class SocketServer extends ServerCommunicator{
	
	private ServerSocket socket;
	public static final int PORT = 32000;
	private boolean keepAlive;	
	
	public SocketServer() {		
		keepAlive = true;		
		try {
			this.socket = new ServerSocket(SocketServer.PORT);
			DeibayLogger.getInstance().getLog().log(Level.INFO, "SocketServer a executar! (Port: " + SocketServer.PORT + ")\n");
		} catch (IOException e) {
			DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Error binding server to port " + SocketServer.PORT + "!\n");
			return;
		}
	}
	
	public void run() {		
		while (keepAlive == true) {
			//System.err.println("OLAAA socketserver");
			
			try {
				Socket clientSocket = this.socket.accept();
				SocketClientCommunicator communicator = new SocketClientCommunicator(clientSocket);
				Thread tCom = new Thread(communicator);
				tCom.start();				
			}catch (IOException e) {
				DeibayLogger.getInstance().getLog().log(Level.SEVERE, "Deu erro na espera por um cliente.\n");				
			}
		}
	}		
	
	public void stop()
	{
		keepAlive = false;
	}
}
